import React, { FC, useEffect, useState } from 'react'
import { Form, Input ,Button} from 'antd-mobile'
import { useNavigate,Link } from 'react-router-dom'
import { reg } from '../../utils/validate'
import { ajax } from '../../api'
import { inject, observer } from 'mobx-react'
import { message } from 'antd'
import Myhead from '../../components/myhead'
const styles:any={
    extraPart:{
        borderLeft: 'solid 1px #eeeeee',
        paddingLeft:' 12px',
        fontSize: '17px',
        lineHeight: '22px'
    }
  }
const Changepass:FC<any>=({uinfo})=> {
    const {userInfo,changeInfo,changeInfoAsync}=uinfo
  const navigator=useNavigate()
  const [form] = Form.useForm()
  

  useEffect(()=>{
    changeInfoAsync()
  },[])

  
    const onFinish=async (values:any)=>{
        form.validateFields().then(value=>{
            console.log(value);
            //表单验证正确了，验证旧密码成功后才能修改面
            console.log(userInfo.password);
            
            if(value.newpass==value.oldpass){
                message.error("新旧密码不能相同")
            }else{
                //查询旧密码是否正确
                if(userInfo.password!=value.oldpass){
                    message.error("旧密码输入错误")
                }else{
                    console.log("修改");
                    
                    ajax.changeuser(value).then(result=>{
                        console.log(result);
                        if(result.code==200){
                            sessionStorage.removeItem('token')
                            changeInfo(null)
                            navigator("/login")
                        }

                        
                    })
                }
            }
            
        }).catch(err=>{
            message.error("请输入有效的密码")
        })
    }
    const onFinishFailed=()=>{
        message.error('请输入正确的表单信息');
    }
    
  return (
    <div>
        <Myhead title="修改密码" back="true"/>
        <Form layout='horizontal' style={{marginTop:'0.44rem'}}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        form={form}
        footer={
          <Button block type='submit' color='primary' size='middle'>
            确认
          </Button>
        }>
          <Form.Item 
          name="oldpass"
          label="旧密码"
          rules={[ 
            { required: true, message: '请输入密码' },
            { pattern:reg.pwd,message:'请输入6-16的数字+字母组合的密码'}
          ]}
          >
            <Input placeholder='请输入旧密码' clearable type='password' />
          </Form.Item>
          <Form.Item 
          name="newpass"
          label="新密码"
          rules={[
            { required: true, message: '请输入密码' },
            { pattern:reg.pwd,message:'请输入6-16的数字+字母组合的密码'}
          ]}
          >
            <Input placeholder='请输入新密码' clearable type='password' />
          </Form.Item>
        </Form>
    </div>
  )
}

export default inject('uinfo')(observer(Changepass))